package com.ruoyi.collection.process;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.base.yaml.BusinessConfig;
import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.domain.RealNameAuth;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.service.IRealNameAuthService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.collection.domain.ApiParameter;
import com.ruoyi.collection.domain.SendRepaymentAccountReq;
import com.ruoyi.collection.process.api.CollectionProcess;
import com.ruoyi.sms.common.SmsUtil;
import com.ruoyi.sms.config.SmsSendConfig;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.sms.service.ISmsService;
import com.ruoyi.sms.util.SmsSignUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 发送还款账号处理
 * @author Victor
 *
 */
@Slf4j
@Service("SendRepaymentAccount")
public class SendRepaymentAccountPorcessor implements CollectionProcess {

    @Autowired
    private ILoanIouService loanIouService;

    @Autowired
    private IRealNameAuthService realNameAuthService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    BusinessConfig businessConfig;

    private static RestTemplate restTemplate;
    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(180000);
        factory.setReadTimeout(180000);
        restTemplate = new RestTemplate(factory);
    }

    /**
     * 短信发送工具类
     */
    private SmsUtil smsUtil = new SmsUtil();
    private SmsSignUtil smsSignUtil = new SmsSignUtil();
    @Autowired
    SmsSendConfig smsSendConfig;


    @SuppressWarnings("unchecked")
    @Override
    public Object process(ApiParameter req) throws Exception {

        log.info("发送还款账号开始");

        SendRepaymentAccountReq reqBody = JSON.parseObject(req.getBody().toString(), SendRepaymentAccountReq.class);

        //获取借据详情
        LoanIou LoanIouQuery = new LoanIou();
        LoanIouQuery.setLoanSerialNo(reqBody.getContrNbr());
        LoanIouQuery.setState(UserConstants.BUSINESS_NORMAL);
        List<LoanIou> loanList = loanIouService.selectLoanIouList(LoanIouQuery);
        if(loanList.size() != 1){
            log.error("发送还款账号时借据数据异常");
            throw new Exception("借据数据异常");
        }

        Date createTime = DateUtils.parse(DateUtils.formatDate(new Date(), DateUtils.YYYYMMDD) + "000000", DateUtils.YYYYMMDDHHMMSS);
//        SmsSendLog smsSendLog = new SmsSendLog();
//        smsSendLog.setTemplateId(Long.parseLong("100015"));
//        smsSendLog.setPhoneNumber(reqBody.getPhone());
//        smsSendLog.setCreateTime(createTime);
        //查询短信服务获取发送记录
        JSONObject jsonObject = smsSignUtil.encryptBASE64();
        JSONObject data = new JSONObject();
        data.put("phoneNumber",reqBody.getPhone());
        data.put("createTime",createTime);
        data.put("templateId",Long.parseLong("100015"));
        jsonObject.put("data",data);
        //接口响应结果
        String result = "";
        try {
            result = smsUtil.sendPost(smsSendConfig.getSmsSendInfoUrl(),jsonObject, null);
            log.info(" -------- get sms send info  :" + result);
        } catch (Exception e) {
            throw new BusinessException(RspEnmu.SMS_SEND_INFO_GET_FAILED);
        }
//        List<SmsSendLog> sendList = collectionMapper.selectSmsSendLogList(smsSendLog);
        JSONObject resultObj = JSONObject.parseObject(result).getJSONObject("data");
        int sendSmsSize = resultObj.getInteger("logSize");
        if(sendSmsSize >= 1){
            log.info("当天已发送1条短信{}", loanList.get(0).getCustNo());
            throw new Exception("This phone number has already received one message. The maxmium message to same phone number is 1 per day.");
        }

        // 获取实名信息
        RealNameAuth realNameAuthCondition = new RealNameAuth();
        realNameAuthCondition.setCustNo(loanList.get(0).getCustNo());
        realNameAuthCondition.setState(BizConstants.BIZ_STATUS_1);
        List<RealNameAuth> authList = realNameAuthService.selectRealNameAuthList(realNameAuthCondition);
        if (CollectionUtils.isEmpty(authList)) {
            log.error("未找到实名信息{}", loanList.get(0).getCustNo());
            throw new Exception("Get Cust Name Fail");
        }

        //验证成功
        Map<String, String> map = createTransferToUs(loanList.get(0).getId());
        if(StringUtils.isEmpty(map.get("accountNumber")) || StringUtils.isEmpty(map.get("bank"))){
            log.error("发送还款账号时获取账号失败");
            throw new Exception("Get Repayment Account Fail");
        }

        SmsSendData smsData = SmsSendData.builder().noticeType(BizConstants.SMS_NOTICE_TYPE_COLLECT).smsType(BizConstants.SMS_TYPE_REPAYMENT_ACCOUNT)
                .countryCode("234").phoneNumber(reqBody.getPhone()).tmplateId("100015").build();

        JSONObject smsParam = new JSONObject();
        smsParam.put("accountNumber", map.get("accountNumber"));
        smsParam.put("bank", map.get("bank"));
        smsParam.put("lastName", authList.get(0).getLastName());
        smsParam.put("currBal", reqBody.getCurrBal());

        smsData.setSmsParam(smsParam);

        smsService.sendSms(smsData);

        log.info("发送还款账号结束");
        return null;

    }

    /**
     * 调用业务系统的数据
     * @param id
     * @return
     */
    private Map<String, String> createTransferToUs(Long id) {
        String url = businessConfig.getApiurl()+"/forcollection/getCreateTransferToUs?id="+id;
        log.info("url:::"+url);
        Map<String, String> map = restTemplate.getForObject(url,Map.class);
        log.info("map>>>>"+map.toString());
        return map;
    }

}
